package com.moleq.dialog;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.SmartBeep;
import com.moleq.device.DeviceManager;
import com.moleq.logic.TransactionManager;
import com.moleq.mgpos.activities.R;
import com.moleq.mgpos.activities.SaleActivity;
import com.moleq.mgpos.widget.NumberPad;
import com.moleq.mgpos.widget.NumberPadButton;
import com.moleq.mgpos.widget.NumberPadForPayment;
import com.moleq.mgpos.widget.NumberPadForPayment.NumberPadListener;
import com.moleq.models.GlobalInfo;
import com.moleq.models.PosSetting;
import com.moleq.models.SaleListItem;
import com.moleq.models.TareSetting;
import com.moleq.service.ServiceManager;
import com.moleq.service.TareSettingService;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;

public class TareDialog extends MoleQBaseDialog {

	private Button mButtonBack, mButtonOk;
	private TransactionManager mPaymentMgr;
	private Context mContext;
	private ListView mListView;
	private List<TareSetting> DataSource = new ArrayList<TareSetting>();
	private TareSettingService service = null;
	private PosSetting possetting = null;
	private OpenTareAdapter mAdapter;
	private NumberPadForPayment numberPanel;
	private DeviceManager mDeviceManager; // contral device scanner or scale
	private SaleListItem mSaleListitem = new SaleListItem();
	private SaleActivity sa;
	private int selectedRow = 0;
	// private double tarevalue = 0;
	// private String weight_unit;
	private TextView tv_tare;

	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			boolean isdismiss = false;
			switch (v.getId()) {
			case R.id.btn_dialog_tare_back:
				if (!mPaymentMgr.getBirthdayDate().equals("") && mPaymentMgr.mSaleListItems.getItemCount() <= 0) {
					mPaymentMgr.setBirthdayDate("");
					ServiceManager.getInstance().mPosTrnsService.UpdateBirthday("null", mPaymentMgr.TransactionNo);
				}

				mDeviceManager.enableAllScanner();
				dismiss();
				break;
			case R.id.btn_dialog_tare_ok:
				Message message1 = new Message();
				message1.what = 2;
				TareDialog.this.myHandler.sendMessage(message1);

				double tareweight = getTotalTare();
				if (tareweight > 0) {
					
					numberPanel.setBuffer("");
					mSaleListitem.setTareWeight(tareweight);
					mSaleListitem.setmTareSetting(DataSource);
					sa.additemdetail();
//					isdismiss = sa.additemdetail();
				}

				Message message2 = new Message();
				message2.what = 1;
				TareDialog.this.myHandler.sendMessage(message2);
//				if (isdismiss) {
				mDeviceManager.enableAllScanner();
				dismiss();
//				}
				break;
			}
		}
	};

	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				mButtonOk.setEnabled(true);
				break;
			case 2:
				mButtonOk.setEnabled(false);
				break;
			}
			super.handleMessage(msg);
		}
	};

	public double getTotalTare() {
		int totalTare = 0;

		for (int i = 0; i < DataSource.size(); i++) {
			totalTare += DataSource.get(i).getQty() * DataSource.get(i).getTa_value();
		}

		return BigDecmialTool.round(totalTare * GlobalInfo.getInstance().tareRate, getUnit());
	}

	public ListView.OnItemClickListener onItemClickListener = new ListView.OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

			switch (parent.getId()) {
			case R.id.lv_dialog_tare_list:
				ScrollToRow(position);
				break;
			}
		}
	};

	public TareDialog(Context context, SaleListItem item) {
		super(context, R.style.dialog, context);
		constructor(context, item);

	}

	public TareDialog(Context context, int theme, SaleListItem item) {
		super(context, theme);
		constructor(context, item);
	}

	private void constructor(Context context, SaleListItem item) {
		// TODO Auto-generated method stub
		mContext = context;
		sa = (SaleActivity) context;
		mSaleListitem = item;
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dialog_tare_selection);
		this.setCancelable(false);
		mDeviceManager = DeviceManager.getInstance();
		mPaymentMgr = TransactionManager.getInstance();

		mButtonBack = (Button) findViewById(R.id.btn_dialog_tare_back);
		mButtonBack.setOnClickListener(mOnClickListener);
		
		mButtonOk = (Button) findViewById(R.id.btn_dialog_tare_ok);
		mButtonOk.setOnClickListener(mOnClickListener);
		mListView = (ListView) findViewById(R.id.lv_dialog_tare_list);
		mListView.setOnItemClickListener(onItemClickListener);
		tv_tare = (TextView) findViewById(R.id.tv_tare_value);

		mAdapter = new OpenTareAdapter(mContext);
		mListView.setAdapter(mAdapter);
		mListView.setDivider(null);
		numberPanel = (NumberPadForPayment) this.findViewById(R.id.NumberPadTare);
		numberPanel.setStyle(NumberPad.SALE_STYLE);
		numberPanel.setNumberPadListener(mNumberPadListener);
		numberPanel.setmMaxLength(3);
	}

	public void show() {
		super.show();

		mDeviceManager.disableAllScanner();
		service = ServiceManager.getInstance().mTareSettingService;
		possetting = ServiceManager.getInstance().mPosSettingService.Find();
		DataSource = service.Find(mSaleListitem.getUpc());
		mAdapter.notifyDataSetChanged();
		tv_tare.setText("Tare(" + GlobalInfo.getInstance().weightUnit + ")");
		numberPanel.setBuffer("");
	}

	private NumberPadListener mNumberPadListener = new NumberPadListener() {

		@Override
		public void onClick(NumberPadButton button) {
			String qty = numberPanel.getBuffer();
			switch (button) {
			case ENTER:
				if (qty.trim().length() > 0) {
					String tmp = numberPanel.getBuffer();
					int paid = Integer.valueOf(tmp);

					if (DataSource.size() > 0) {
						TareSetting tare = DataSource.get(selectedRow);
						tare.setQty(paid);
						DataSource.set(selectedRow, tare);
						mAdapter.notifyDataSetChanged();
					}
				}
				numberPanel.setBuffer("");
				break;
			case DOT:
				qty = qty.replace(".", "");
				numberPanel.setBuffer(qty);
				break;
			default:
				//
				break;
			}
		}

	};

	class OpenTareAdapter extends BaseAdapter {
		private Context maContext;

		public final class ViewHolder {
			public TextView tv_tare_name;
			public TextView tv_tare_qty;
			public TextView tv_tare_value;
		}

		public OpenTareAdapter(Context context) {
			maContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return DataSource.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return DataSource.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();

				convertView = LayoutInflater.from(maContext).inflate(R.layout.tare_list_item, null);
				holder.tv_tare_name = (TextView) convertView.findViewById(R.id.tv_tare_name);
				holder.tv_tare_qty = (TextView) convertView.findViewById(R.id.tv_tare_qty);
				holder.tv_tare_value = (TextView) convertView.findViewById(R.id.tv_tare_value);
				convertView.setOnTouchListener(onItemTouchListener);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			String content = DataSource.get(position).getTa_desc();
			String qty = String.valueOf(DataSource.get(position).getQty());
			String value = MoleQUtil.fixWeight(DataSource.get(position).getTa_value() * GlobalInfo.getInstance().tareRate, getUnit());

			holder.tv_tare_name.setText(content);
			holder.tv_tare_qty.setText(qty);
			holder.tv_tare_value.setText(value);

			if (position == selectedRow) {
				holder.tv_tare_name.setBackgroundColor(Color.rgb(255, 219, 16));
				holder.tv_tare_qty.setBackgroundColor(Color.rgb(255, 219, 16));
				holder.tv_tare_value.setBackgroundColor(Color.rgb(255, 219, 16));
			} else {
				holder.tv_tare_name.setBackgroundColor(Color.rgb(204, 204, 204));
				holder.tv_tare_qty.setBackgroundColor(Color.rgb(204, 204, 204));
				holder.tv_tare_value.setBackgroundColor(Color.rgb(204, 204, 204));
			}

			return convertView;
		}

	}

	private OnTouchListener onItemTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				SmartBeep.getInstance().play(SmartBeep.SOUND_CLICK);
			}
			return false;
		}

	};

	public void ScrollToRow(int row) {
		selectedRow = row;
		mAdapter.notifyDataSetChanged();
	}

	public int GetSelectedIndex() {
		return selectedRow;
	}

	public int getUnit() {
		int checkunit = 2;
		String unit = possetting.getPs_weight_unit();
		if (unit.equals("oz")) {
			checkunit = 1;
		} else if (unit.equals("lb")) {
			checkunit = 2;
		} else if (unit.equals("kg")) {
			checkunit = 3;
		}

		return checkunit;
	}

}
